// pages/cart/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    addressCache:{},
    arrayList:[],
    allMoney:0,
    allNum:0,
    allCheck:false
  },
  //按钮点击事件
  addressClick(){
    wx.chooseAddress({
      success: (result) => {
        wx.setStorageSync('cache', result)
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let addressCache = wx.getStorageSync('cache')
    
    let arrayList = wx.getStorageSync('cart')||[]

    this.setNum(arrayList)
    this.setData({
      addressCache,
    })
  },
  //设置商品选择框的方法
  handleCheckList(e){
    let goods_id = e.currentTarget.dataset.id
    let {arrayList} = this.data
    let index = arrayList.findIndex(v=>v.goods_id === goods_id)
    arrayList[index].isCheck = !arrayList[index].isCheck

    this.setNum(arrayList)
  },

  //设置全选反选方法
  bindTapAllCheck(){
    let {allCheck} = this.data
    let {arrayList} = this.data

    allCheck = !allCheck
    arrayList.forEach(v => v.isCheck = allCheck)
    this.setNum(arrayList)
  },

  //设置商品数量加减的方法
  handleNumAdd(e){
    const {option,id} = e.currentTarget.dataset;
    let {arrayList} = this.data;

    const index = arrayList.findIndex(v => v.goods_id===id);
    if(arrayList[index].num===1 && option === -1){
      wx.showModal({
        title: '提示',
        content: '确定要删除吗',
        success: (res) =>{
          if (res.confirm) {
            arrayList.splice(index,1)
            this.setNum(arrayList)
          } else if (res.cancel) {
          }
        }
      })
    }else{
      arrayList[index].num+=option;
      this.setNum(arrayList)
    }
  },

  //设置结算按钮方法
  handleSettlement(){
    let {addressCache,allNum} = this.data
    if(!addressCache.userName){
      wx.showToast({
        title: '您还没有选择地址',
        icon: 'none',
      });
    }
    else if(allNum===0){
      wx.showToast({
        title: '您还没有添加商品',
        icon: 'none',
      });
    }else{
    wx.navigateTo({
      url: '../pay/index',
    })
    }
  },

  //封装方法
  setNum(arrayList){
    let allCheck = true
    let allMoney = 0
    let allNum = 0
    arrayList.forEach(v=>{
      if(v.isCheck){
        allMoney += v.num * v.goods_price;
        allNum += v.num;
      }else{
        allCheck = false
      }
    })
    allCheck = arrayList.length!=0?allCheck:false
    this.setData({
      arrayList,
      allCheck:allCheck,
      allMoney,
      allNum
    })

    wx.setStorageSync('cart', arrayList)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})